// 游戏常量和配置
const GRID_SIZE = 20; // 网格大小
const INITIAL_SNAKE_LENGTH = 3; // 初始蛇的长度
const CANVAS_SIZE = 400;
const GRID_COUNT = CANVAS_SIZE / GRID_SIZE;

// 游戏变量
let canvas, ctx;
let snake = [];
let food = {};
let direction = "right";
let nextDirection = "right";
let gameLoop;
let score = 0;
let highScore = localStorage.getItem("snakeHighScore") || 0;
let currentLevel = 1;
let gameSpeed = 200; // 初始游戏速度（毫秒）
let isPaused = false;
let obstacles = []; // 障碍物数组
let specialFood = null; // 特殊食物
let isGameOver = false;
let snakeColor = "#4CAF50";
let foodColors = ["#FF5252", "#FF4081", "#E040FB", "#7C4DFF", "#536DFE"];
let lastKeyPressTime = 0;

// 游戏屏幕元素
const startScreen = document.getElementById("start-screen");
const gameScreen = document.getElementById("game-screen");
const gameOverScreen = document.getElementById("game-over-screen");
const levelBtns = document.querySelectorAll(".level-btn");
const startBtn = document.getElementById("start-btn");
const pauseBtn = document.getElementById("pause-btn");
const restartBtn = document.getElementById("restart-btn");
const playAgainBtn = document.getElementById("play-again-btn");
const changeLevelBtn = document.getElementById("change-level-btn");

// 得分元素
const scoreElement = document.getElementById("score");
const highScoreElement = document.getElementById("high-score");
const finalScoreElement = document.getElementById("final-score");
const currentLevelElement = document.getElementById("current-level");

// 初始化
function init() {
  canvas = document.getElementById("game-canvas");
  ctx = canvas.getContext("2d");

  highScoreElement.textContent = highScore;
  currentLevelElement.textContent = currentLevel;

  // 级别选择按钮事件
  levelBtns.forEach((btn) => {
    btn.addEventListener("click", () => {
      levelBtns.forEach((b) => b.classList.remove("active"));
      btn.classList.add("active");
      currentLevel = parseInt(btn.getAttribute("data-level"));
      currentLevelElement.textContent = currentLevel;
      updateGameSpeed();
    });
  });

  // 游戏按钮事件
  startBtn.addEventListener("click", startGame);
  pauseBtn.addEventListener("click", togglePause);
  restartBtn.addEventListener("click", restartGame);
  playAgainBtn.addEventListener("click", restartGame);
  changeLevelBtn.addEventListener("click", showStartScreen);

  // 键盘控制
  document.addEventListener("keydown", handleKeyDown);

  // 触摸屏控制
  setupTouchControls();

  // 默认选择1级
  document.querySelector('.level-btn[data-level="1"]').classList.add("active");

  // 加载图片资源
  loadAssets();
}

// 加载图片和音效资源
function loadAssets() {
  // 暂时使用纯色，后续可以加载更多图片资源
}

// 更新游戏速度
function updateGameSpeed() {
  // 根据级别调整游戏速度
  gameSpeed = 200 - (currentLevel - 1) * 10;
  gameSpeed = Math.max(gameSpeed, 50); // 最快速度限制
}

// 设置触摸控制
function setupTouchControls() {
  let touchStartX = 0;
  let touchStartY = 0;

  canvas.addEventListener(
    "touchstart",
    (e) => {
      touchStartX = e.touches[0].clientX;
      touchStartY = e.touches[0].clientY;
      e.preventDefault();
    },
    false
  );

  canvas.addEventListener(
    "touchmove",
    (e) => {
      e.preventDefault();
    },
    false
  );

  canvas.addEventListener(
    "touchend",
    (e) => {
      const touchEndX = e.changedTouches[0].clientX;
      const touchEndY = e.changedTouches[0].clientY;

      const diffX = touchEndX - touchStartX;
      const diffY = touchEndY - touchStartY;

      // 判断滑动方向
      if (Math.abs(diffX) > Math.abs(diffY)) {
        // 水平滑动
        if (diffX > 0 && direction !== "left") {
          nextDirection = "right";
        } else if (diffX < 0 && direction !== "right") {
          nextDirection = "left";
        }
      } else {
        // 垂直滑动
        if (diffY > 0 && direction !== "up") {
          nextDirection = "down";
        } else if (diffY < 0 && direction !== "down") {
          nextDirection = "up";
        }
      }

      e.preventDefault();
    },
    false
  );
}

// 处理键盘输入
function handleKeyDown(e) {
  const now = Date.now();
  // 限制按键响应频率
  if (now - lastKeyPressTime < 50) return;
  lastKeyPressTime = now;

  switch (e.key) {
    case "ArrowUp":
    case "w":
    case "W":
      if (direction !== "down") nextDirection = "up";
      break;
    case "ArrowDown":
    case "s":
    case "S":
      if (direction !== "up") nextDirection = "down";
      break;
    case "ArrowLeft":
    case "a":
    case "A":
      if (direction !== "right") nextDirection = "left";
      break;
    case "ArrowRight":
    case "d":
    case "D":
      if (direction !== "left") nextDirection = "right";
      break;
    case " ":
      togglePause();
      break;
  }
}

// 显示开始屏幕
function showStartScreen() {
  hideAllScreens();
  startScreen.classList.add("active");
}

// 隐藏所有屏幕
function hideAllScreens() {
  startScreen.classList.remove("active");
  gameScreen.classList.remove("active");
  gameOverScreen.classList.remove("active");
}

// 启动游戏
function startGame() {
  hideAllScreens();
  gameScreen.classList.add("active");

  resetGame();
  createFood();
  createObstacles();

  gameLoop = setInterval(update, gameSpeed);
}

// 重置游戏状态
function resetGame() {
  // 初始化蛇
  snake = [];
  for (let i = INITIAL_SNAKE_LENGTH - 1; i >= 0; i--) {
    snake.push({ x: i, y: 0 });
  }

  direction = "right";
  nextDirection = "right";
  score = 0;
  isGameOver = false;
  isPaused = false;
  obstacles = [];
  specialFood = null;

  scoreElement.textContent = score;
  pauseBtn.textContent = "暂停";

  updateGameSpeed();
}

// 创建食物
function createFood() {
  let validPosition = false;
  while (!validPosition) {
    food = {
      x: Math.floor(Math.random() * GRID_COUNT),
      y: Math.floor(Math.random() * GRID_COUNT),
      color: foodColors[Math.floor(Math.random() * foodColors.length)],
    };

    validPosition = true;

    // 确保食物不在蛇身上
    for (let segment of snake) {
      if (segment.x === food.x && segment.y === food.y) {
        validPosition = false;
        break;
      }
    }

    // 确保食物不在障碍物上
    for (let obstacle of obstacles) {
      if (obstacle.x === food.x && obstacle.y === food.y) {
        validPosition = false;
        break;
      }
    }
  }

  // 一定概率生成特殊食物
  if (Math.random() < 0.1 && currentLevel > 5) {
    createSpecialFood();
  }
}

// 创建特殊食物
function createSpecialFood() {
  let validPosition = false;
  while (!validPosition) {
    specialFood = {
      x: Math.floor(Math.random() * GRID_COUNT),
      y: Math.floor(Math.random() * GRID_COUNT),
      color: "#FFD700", // 金色
      points: 5, // 特殊食物得分
      timer: 50, // 特殊食物存在的帧数
    };

    validPosition = true;

    // 确保特殊食物不在蛇身上
    for (let segment of snake) {
      if (segment.x === specialFood.x && segment.y === specialFood.y) {
        validPosition = false;
        break;
      }
    }

    // 确保特殊食物不在普通食物上
    if (food.x === specialFood.x && food.y === specialFood.y) {
      validPosition = false;
    }

    // 确保特殊食物不在障碍物上
    for (let obstacle of obstacles) {
      if (obstacle.x === specialFood.x && obstacle.y === specialFood.y) {
        validPosition = false;
        break;
      }
    }
  }
}

// 创建障碍物
function createObstacles() {
  // 根据级别创建障碍物
  const obstacleCount = Math.floor(currentLevel / 3); // 每3级增加一个障碍物

  for (let i = 0; i < obstacleCount; i++) {
    let validPosition = false;
    let obstacle;

    while (!validPosition) {
      obstacle = {
        x: Math.floor(Math.random() * GRID_COUNT),
        y: Math.floor(Math.random() * GRID_COUNT),
        color: "#795548", // 棕色
      };

      validPosition = true;

      // 确保障碍物不在蛇身上
      for (let segment of snake) {
        if (segment.x === obstacle.x && segment.y === obstacle.y) {
          validPosition = false;
          break;
        }
      }

      // 确保障碍物不在食物上
      if (food.x === obstacle.x && food.y === obstacle.y) {
        validPosition = false;
      }

      // 确保障碍物不在其他障碍物上
      for (let existingObstacle of obstacles) {
        if (
          existingObstacle.x === obstacle.x &&
          existingObstacle.y === obstacle.y
        ) {
          validPosition = false;
          break;
        }
      }

      // 确保障碍物不在蛇头前方附近，留出一些空间
      const head = snake[0];
      if (Math.abs(head.x - obstacle.x) + Math.abs(head.y - obstacle.y) < 5) {
        validPosition = false;
      }
    }

    obstacles.push(obstacle);
  }

  // 在高级别添加特殊障碍模式
  if (currentLevel >= 10) {
    // 边界障碍
    for (let i = 0; i < GRID_COUNT; i++) {
      if (currentLevel >= 13 && i % 2 === 0) {
        // 13级以上的特殊模式：边界上有间隔的障碍物
        obstacles.push({ x: i, y: 0, color: "#795548" });
        obstacles.push({ x: i, y: GRID_COUNT - 1, color: "#795548" });
        obstacles.push({ x: 0, y: i, color: "#795548" });
        obstacles.push({ x: GRID_COUNT - 1, y: i, color: "#795548" });
      } else if (currentLevel >= 10 && currentLevel < 13 && i % 3 === 0) {
        // 10-12级的特殊模式：边界上有更大间隔的障碍物
        obstacles.push({ x: i, y: 0, color: "#795548" });
        obstacles.push({ x: i, y: GRID_COUNT - 1, color: "#795548" });
        obstacles.push({ x: 0, y: i, color: "#795548" });
        obstacles.push({ x: GRID_COUNT - 1, y: i, color: "#795548" });
      }
    }
  }
}

// 暂停/恢复游戏
function togglePause() {
  isPaused = !isPaused;
  pauseBtn.textContent = isPaused ? "继续" : "暂停";

  if (isPaused) {
    clearInterval(gameLoop);
  } else {
    gameLoop = setInterval(update, gameSpeed);
  }
}

// 游戏重新开始
function restartGame() {
  clearInterval(gameLoop);
  hideAllScreens();
  gameScreen.classList.add("active");

  resetGame();
  createFood();
  createObstacles();

  gameLoop = setInterval(update, gameSpeed);
}

// 游戏结束处理
function endGame() {
  clearInterval(gameLoop);
  isGameOver = true;

  if (score > highScore) {
    highScore = score;
    localStorage.setItem("snakeHighScore", highScore);
    highScoreElement.textContent = highScore;
  }

  finalScoreElement.textContent = score;

  setTimeout(() => {
    hideAllScreens();
    gameOverScreen.classList.add("active");
  }, 1000);
}

// 游戏主循环逻辑
function update() {
  if (isPaused || isGameOver) return;

  direction = nextDirection;

  // 保存旧蛇头，用于后续添加新蛇头
  const head = { ...snake[0] };

  // 更新蛇头位置
  switch (direction) {
    case "up":
      head.y -= 1;
      break;
    case "down":
      head.y += 1;
      break;
    case "left":
      head.x -= 1;
      break;
    case "right":
      head.x += 1;
      break;
  }

  // 根据级别检查边界碰撞
  if (currentLevel <= 5) {
    // 级别1-5：碰到墙壁游戏结束
    if (
      head.x < 0 ||
      head.x >= GRID_COUNT ||
      head.y < 0 ||
      head.y >= GRID_COUNT
    ) {
      endGame();
      return;
    }
  } else {
    // 级别6及以上：穿墙效果
    if (head.x < 0) head.x = GRID_COUNT - 1;
    else if (head.x >= GRID_COUNT) head.x = 0;

    if (head.y < 0) head.y = GRID_COUNT - 1;
    else if (head.y >= GRID_COUNT) head.y = 0;
  }

  // 检查是否撞到自己
  for (let i = 0; i < snake.length; i++) {
    if (snake[i].x === head.x && snake[i].y === head.y) {
      endGame();
      return;
    }
  }

  // 检查是否撞到障碍物
  for (let obstacle of obstacles) {
    if (head.x === obstacle.x && head.y === obstacle.y) {
      endGame();
      return;
    }
  }

  // 添加新蛇头
  snake.unshift(head);

  // 检查是否吃到食物
  let ate = false;
  if (head.x === food.x && head.y === food.y) {
    score += 1;
    scoreElement.textContent = score;
    createFood();
    ate = true;
  }

  // 检查是否吃到特殊食物
  if (specialFood && head.x === specialFood.x && head.y === specialFood.y) {
    score += specialFood.points;
    scoreElement.textContent = score;
    specialFood = null;
    ate = true;
  }

  // 如果没有吃到食物，移除蛇尾
  if (!ate) {
    snake.pop();
  }

  // 更新特殊食物计时器
  if (specialFood) {
    specialFood.timer--;
    if (specialFood.timer <= 0) {
      specialFood = null;
    }
  }

  // 绘制游戏画面
  drawGame();
}

// 绘制游戏画面
function drawGame() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制网格背景
  drawGrid();

  // 绘制障碍物
  drawObstacles();

  // 绘制食物
  drawFood();

  // 绘制特殊食物
  if (specialFood) {
    drawSpecialFood();
  }

  // 绘制蛇
  drawSnake();
}

// 绘制网格
function drawGrid() {
  ctx.strokeStyle = "#e0e0e0";
  ctx.lineWidth = 0.5;

  // 绘制垂直线
  for (let i = 0; i <= GRID_COUNT; i++) {
    ctx.beginPath();
    ctx.moveTo(i * GRID_SIZE, 0);
    ctx.lineTo(i * GRID_SIZE, CANVAS_SIZE);
    ctx.stroke();
  }

  // 绘制水平线
  for (let i = 0; i <= GRID_COUNT; i++) {
    ctx.beginPath();
    ctx.moveTo(0, i * GRID_SIZE);
    ctx.lineTo(CANVAS_SIZE, i * GRID_SIZE);
    ctx.stroke();
  }
}

// 绘制蛇
function drawSnake() {
  snake.forEach((segment, index) => {
    // 蛇头与身体使用不同颜色
    if (index === 0) {
      ctx.fillStyle = "#388E3C"; // 蛇头深绿色
    } else {
      ctx.fillStyle = snakeColor;
    }

    const x = segment.x * GRID_SIZE;
    const y = segment.y * GRID_SIZE;

    // 圆角矩形效果
    ctx.beginPath();
    ctx.roundRect(x + 1, y + 1, GRID_SIZE - 2, GRID_SIZE - 2, 5);
    ctx.fill();

    // 蛇头上添加眼睛
    if (index === 0) {
      ctx.fillStyle = "white";

      // 根据方向调整眼睛位置
      if (direction === "right") {
        ctx.beginPath();
        ctx.arc(x + GRID_SIZE - 7, y + 7, 2, 0, Math.PI * 2);
        ctx.arc(x + GRID_SIZE - 7, y + GRID_SIZE - 7, 2, 0, Math.PI * 2);
        ctx.fill();
      } else if (direction === "left") {
        ctx.beginPath();
        ctx.arc(x + 7, y + 7, 2, 0, Math.PI * 2);
        ctx.arc(x + 7, y + GRID_SIZE - 7, 2, 0, Math.PI * 2);
        ctx.fill();
      } else if (direction === "up") {
        ctx.beginPath();
        ctx.arc(x + 7, y + 7, 2, 0, Math.PI * 2);
        ctx.arc(x + GRID_SIZE - 7, y + 7, 2, 0, Math.PI * 2);
        ctx.fill();
      } else if (direction === "down") {
        ctx.beginPath();
        ctx.arc(x + 7, y + GRID_SIZE - 7, 2, 0, Math.PI * 2);
        ctx.arc(x + GRID_SIZE - 7, y + GRID_SIZE - 7, 2, 0, Math.PI * 2);
        ctx.fill();
      }
    }
  });
}

// 绘制食物
function drawFood() {
  const x = food.x * GRID_SIZE;
  const y = food.y * GRID_SIZE;

  ctx.fillStyle = food.color;

  // 苹果形状
  ctx.beginPath();
  ctx.arc(
    x + GRID_SIZE / 2,
    y + GRID_SIZE / 2 + 2,
    GRID_SIZE / 2 - 3,
    0,
    Math.PI * 2
  );
  ctx.fill();

  // 苹果柄
  ctx.fillStyle = "#795548";
  ctx.fillRect(x + GRID_SIZE / 2 - 1, y + 4, 2, 4);

  // 苹果叶
  ctx.fillStyle = "#8BC34A";
  ctx.beginPath();
  ctx.ellipse(x + GRID_SIZE / 2 + 3, y + 6, 3, 2, Math.PI / 4, 0, Math.PI * 2);
  ctx.fill();
}

// 绘制特殊食物
function drawSpecialFood() {
  const x = specialFood.x * GRID_SIZE;
  const y = specialFood.y * GRID_SIZE;

  ctx.fillStyle = specialFood.color;

  // 闪烁效果
  if (specialFood.timer % 5 < 3) {
    // 星星形状
    ctx.beginPath();
    ctx.moveTo(x + GRID_SIZE / 2, y + 3);
    ctx.lineTo(x + GRID_SIZE / 2 + 4, y + GRID_SIZE / 2 - 2);
    ctx.lineTo(x + GRID_SIZE - 3, y + GRID_SIZE / 2 - 1);
    ctx.lineTo(x + GRID_SIZE / 2 + 5, y + GRID_SIZE / 2 + 3);
    ctx.lineTo(x + GRID_SIZE - 2, y + GRID_SIZE - 3);
    ctx.lineTo(x + GRID_SIZE / 2, y + GRID_SIZE / 2 + 5);
    ctx.lineTo(x + 3, y + GRID_SIZE - 3);
    ctx.lineTo(x + GRID_SIZE / 2 - 4, y + GRID_SIZE / 2 + 3);
    ctx.lineTo(x + 3, y + GRID_SIZE / 2 - 1);
    ctx.lineTo(x + GRID_SIZE / 2 - 3, y + GRID_SIZE / 2 - 2);
    ctx.closePath();
    ctx.fill();
  }
}

// 绘制障碍物
function drawObstacles() {
  obstacles.forEach((obstacle) => {
    const x = obstacle.x * GRID_SIZE;
    const y = obstacle.y * GRID_SIZE;

    ctx.fillStyle = obstacle.color;

    // 石头形状
    ctx.beginPath();
    ctx.roundRect(x + 1, y + 1, GRID_SIZE - 2, GRID_SIZE - 2, [8, 3, 6, 2]);
    ctx.fill();

    // 添加纹理
    ctx.strokeStyle = "#5D4037";
    ctx.lineWidth = 1;

    // 随机纹理线条
    ctx.beginPath();
    ctx.moveTo(x + 5, y + 5);
    ctx.lineTo(x + 10, y + 8);
    ctx.moveTo(x + 12, y + 12);
    ctx.lineTo(x + 15, y + 15);
    ctx.stroke();
  });
}

// 初始化游戏
window.addEventListener("DOMContentLoaded", init);
